﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace NumberToWords
{
    public class NumberToWordsService : INumberToWordsService
    {
        private NumberToLetterConverter converter;
        private NumberTrie trie;
        private Random random;

        public NumberToWordsService()
        {
            this.converter = NumberToLetterConverter.CreateStandardPhoneConverter();
            this.trie = new NumberTrie(this.converter);
            this.random = new Random();
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            StreamReader reader = new StreamReader(baseDirectory + "\\new_words.txt");
            while(reader.Peek() != -1)
            {
                String line = reader.ReadLine();
                trie.Add(line);
            }
        }

        private string GetMatch(string value)
        {
            List<string> potentialWords = new List<string>(this.trie.FindMatches(value));
            if (potentialWords.Count > 0)
            {
                return potentialWords[this.random.Next(0, potentialWords.Count)];
            }
            return null;
        }

        public string Number2Words(string value)
        {
            string fullResult = "";
            string partialResult = "";
            foreach(char c in value)
            {
                if (c.Equals('1') || c.Equals('0'))
                {
                    if (partialResult.Length > 0)
                    {
                        string replacedResult = this.GetMatch(partialResult);
                        if (replacedResult == null)
                        {
                            return null;
                        }
                        fullResult += replacedResult;
                        partialResult = "";
                    }
                    fullResult += c;
                }
                else
                {
                    partialResult += c;
                }
            }
            if (partialResult.Length > 0)
            {
                string replacedResult = this.GetMatch(partialResult);
                if (replacedResult == null)
                {
                    return null;
                }
                fullResult += replacedResult;
                partialResult = "";
            }
            return fullResult;
        }
    }
}
